import { ref } from 'vue'
import { defineStore } from 'pinia'
import { login as loginApi, getUserInfo } from '@/api/index'
interface userStateClass {
  token: string
  roles: []
  menuList: []
  userInfo: Object
}

export const useUserStore = defineStore('userState', () => {

  /**用户全部信息 */
  let userState = {} as userStateClass
  const token = ref('') // 令牌
  const roles = ref([]) // 角色
  const menuList = ref([]) // 菜单
  const userInfo = ref({}) // 用户信息

  if (localStorage.userState) { // 如果缓存中有登录状态
    userState = JSON.parse(localStorage.userState)
    /**缓存中的user信息 */
    token.value = userState.token
    roles.value = userState.roles
    menuList.value = userState.menuList
    userInfo.value = userState.userInfo
  }

  // 登录
  const login = (_userInfo: { username: string; password: string }) => {
    return new Promise(async (resolve, reject) => {
      const res_login = await loginApi(_userInfo).catch(() => false)
      if (!res_login) return reject()
      await getInfo(_userInfo.username)
      resolve(_userInfo.username)
    })
  }
  // 获取用户信息
  const getInfo = (username: String) => {
    return new Promise(async (resolve, reject) => {
      const _userState = await getUserInfo(username).catch((err) => err)
      userState = _userState.data
      token.value = userState.token
      roles.value = userState.roles
      menuList.value = userState.menuList
      userInfo.value = userState.userInfo
      localStorage.userState = JSON.stringify(userState)
      resolve(_userState.data)
    })
  }
  // 退出
  const logout = () => {
    return new Promise((resolve, reject) => {
      token.value = ''
      roles.value = []
      menuList.value = []
      userInfo.value = {}
      localStorage.removeItem('userState')
      resolve(1)
    })
  }

  return { token, userState, roles, menuList, userInfo, login, getInfo, logout }
})
